package com.tj.collection.task;

import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.EntityUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.tj.collection.db.dao.ClReceiverDao;
import com.tj.collection.db.dao.ClReceiverDetailDao;
import com.tj.collection.db.entity.ClReceiverDetailEntity;
import com.tj.collection.db.entity.ClReceiverEntity;
import com.tj.collection.db.entity.business.ClReceiverInfoEntity;
import com.tj.collection.enums.MessageSceneEnum;
import com.tj.collection.integration.MessageIntegrationService;
import com.tj.collection.service.dto.CollectionOrderVo;
import com.tj.collection.utils.ConfigUtil;
import com.tj.collection.utils.HttpUtil;
import com.tj.collection.utils.MessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: pavan
 * Date: 2019/9/12
 * Time: 下午3:53
 */
@Component
public class NotifyOverDueTaskJob implements SimpleJob {

    private static final Log LOGGER = LogFactory.getLog(NotifyOverDueTaskJob.class);
    @Autowired
    private MessageIntegrationService messageIntegrationService;
    @Autowired
    private ConfigUtil configUtil;
    @Autowired
    private MessageUtils messageUtils;
    @Autowired
    private ClReceiverDetailDao clReceiverDetailDao;
    @Autowired
    private ClReceiverDao clReceiverDao;

    @Override
    public void execute(ShardingContext shardingContext) {
        String taskSwitch = configUtil.getNotifyOverDueSwitch();
        if (StringUtils.isEmpty(taskSwitch) || taskSwitch.equals("false")) {
            LOGGER.info("通知逾期短信任务未开启");
            return;
        }

        try {
            LOGGER.info("NotifyOverDueTaskJob,通知已经逾期的账单任务开始");
            this.notifyOverDueOrder(Lists.newArrayList(1, 2, 3));
            LOGGER.info("NotifyOverDueTaskJob,通知已经逾期的账单任务结束");
        } catch (Exception e) {
            LOGGER.error("NotifyOverDueTaskJob异常", e);
        }
    }

    /**
     * 账单逾期提醒
     */
    public void notifyOverDueOrder(List<Integer> overdueDaysList) {
        Map<String, Object> params = new HashMap<>();
        if (CollectionUtils.isEmpty(overdueDaysList)) {
            overdueDaysList = Lists.newArrayList(1, 2, 3);
        }
        params.put("overdueDaysList", overdueDaysList);
        List<ClReceiverInfoEntity> clReceiverInfoEntityList = clReceiverDetailDao.selectOverdueNeedNotifyOrderBill(params);
        LOGGER.info("notifyOverDueOrder,逾期通知,overdueDaysList:{},size:{}", overdueDaysList.toString(), clReceiverInfoEntityList.size());
        if (CollectionUtils.isEmpty(clReceiverInfoEntityList)) {
            LOGGER.error("截止到{},还未有已经逾期的账单", new Date());
            return;
        }
        Map<Integer, List<ClReceiverInfoEntity>> clReceiverInfoEntityListMap = EntityUtils.makeEntityListMap(clReceiverInfoEntityList, "overdueDays");
        for (Map.Entry<Integer, List<ClReceiverInfoEntity>> entry : clReceiverInfoEntityListMap.entrySet()) {
            for (ClReceiverInfoEntity clReceiverInfoEntity : entry.getValue()) {
                LOGGER.info("账单通知处理,userCode:{},collectionNo:{}", clReceiverInfoEntity.getUserCode(), clReceiverInfoEntity.getCollectionNo());
                // msg
                sendMsg(clReceiverInfoEntity);
                // mail
                sendMail(clReceiverInfoEntity);
            }
        }
    }

    /**
     * 账单逾期提醒
     */
    public void sendOneNotifyOverDueOrder(String collectionNo) {
        ClReceiverEntity clReceiverEntity = clReceiverDao.selectByCollectionNo(collectionNo);
        ClReceiverDetailEntity clReceiverDetailEntity = clReceiverDetailDao.selectOneByCollectionNo(collectionNo);
        LOGGER.info("账单通知处理,userCode:{},collectionNo:{}", clReceiverEntity.getUserCode(), clReceiverEntity.getCollectionNo());

        ClReceiverInfoEntity clReceiverInfoEntity = new ClReceiverInfoEntity();
        clReceiverInfoEntity.setUserCode(clReceiverEntity.getUserCode());
        clReceiverInfoEntity.setRepaymentDate(clReceiverDetailEntity.getRepaymentDate());
        clReceiverInfoEntity.setName(clReceiverDetailEntity.getName());
        clReceiverInfoEntity.setMobile(clReceiverDetailEntity.getMobile());
        clReceiverInfoEntity.setOrderNo(clReceiverEntity.getOrderNo());
        clReceiverInfoEntity.setBorrowCapital(clReceiverDetailEntity.getBorrowCapital());
        clReceiverInfoEntity.setOverdueDays(DateUtil.diffDate(new Date(), clReceiverDetailEntity.getRepaymentDate()));
        // msg
        sendMsg(clReceiverInfoEntity);
        // mail
        sendMail(clReceiverInfoEntity);
    }

    private void sendMail(ClReceiverInfoEntity clReceiverInfoEntity) {
        try {
            Date repaymentDate = clReceiverInfoEntity.getRepaymentDate();
            String format = new SimpleDateFormat("MMM dd", Locale.ENGLISH).format(repaymentDate);

            String url = messageUtils.getMailBasicTemplateUrl(clReceiverInfoEntity.getUserCode(), clReceiverInfoEntity.getOrderNo());
            String mailContent = HttpUtil.getPage(url);
            mailContent = mailContent.replace("__content__", configUtil.getMsgMailOverdueReminderContent());
            mailContent = mailContent.replace("__Users Name__", Strings.nullToEmpty(clReceiverInfoEntity.getName()));
            mailContent = mailContent.replace("__Mobile No.__", Strings.nullToEmpty(clReceiverInfoEntity.getMobile()));
            mailContent = mailContent.replace("__Order ID__", Strings.nullToEmpty(clReceiverInfoEntity.getOrderNo()));

            mailContent = mailContent.replace("__amount__", clReceiverInfoEntity.getBorrowCapital().toString());
//            mailContent = mailContent.replace("__overdueTime__", format);
            mailContent = mailContent.replace("__overdueDay__", String.valueOf(clReceiverInfoEntity.getOverdueDays()));

            messageIntegrationService.loanNoteByEmail(clReceiverInfoEntity.getUserCode(), clReceiverInfoEntity.getOrderNo(), mailContent, "Repayment Notice");
        } catch (Exception e) {
            LOGGER.error("sendMail error", e);
        }

    }

    private void sendMsg(ClReceiverInfoEntity clReceiverInfoEntity) {
        try {
            String overdueDaysStr = "" + clReceiverInfoEntity.getOverdueDays();
            int overdueDays = clReceiverInfoEntity.getOverdueDays();
            if (overdueDays == 1) {
                overdueDaysStr = "one day";
            }
            if (overdueDays == 2) {
                overdueDaysStr = "two days";
            }
            if (overdueDays == 3) {
                overdueDaysStr = "three days";
            }

//            SingleSmsSendRequestRO smsSendRequestRO = new SingleSmsSendRequestRO();
//            String mobile = clReceiverInfoEntity.getMobile();
//            smsSendRequestRO.setPhone(mobile);
//            String messageBizCode = messageUtils.getMessageBizCodeByPackageName(clReceiverInfoEntity.getUserCode(), clReceiverInfoEntity.getOrderNo(), MessageSceneEnum.SMS_OVERDUE_REMINDER);
//            smsSendRequestRO.setBizCode(messageBizCode);
//            Map<String, String> paramMap = this.getParamList(clReceiverInfoEntity, clReceiverInfoEntity.getOverdueDays(), overdueDaysStr);
//            smsSendRequestRO.setReplaceParam(paramMap);
//            smsSendRequestRO.setUserCode(clReceiverInfoEntity.getUserCode());
//            LOGGER.info("发送逾期短信,smsSendRequestRO:{}", JSON.toJSONString(smsSendRequestRO));
//            messageIntegrationService.send(smsSendRequestRO);
        } catch (Exception e) {
            LOGGER.error("send msg error", e);
        }
    }

    /**
     * 按照逾期维度的统计账单
     *
     * @param collectionOrderVos 账单
     * @param overDueDays        逾期天数
     * @return
     */
    private Map<Integer, List<CollectionOrderVo>> getCollectionOrderMap(List<CollectionOrderVo> collectionOrderVos, List<Integer> overDueDays) {
        this.calculateOverdueDays(collectionOrderVos);
        Map<Integer, List<CollectionOrderVo>> allOrderBillMap = collectionOrderVos.stream().collect(Collectors.groupingBy(CollectionOrderVo::getOverdueDays));
        Map<Integer, List<CollectionOrderVo>> orderBillMap = new HashMap<>();
        for (Integer overDueDay : overDueDays) {
            List<CollectionOrderVo> collectionOrderVoList = allOrderBillMap.get(overDueDay);
            if (CollectionUtils.isEmpty(collectionOrderVoList)) {
                continue;
            }
            orderBillMap.put(overDueDay, collectionOrderVoList);
        }
        return orderBillMap;
    }

    /**
     * 统计逾期天数
     *
     * @param collectionOrderVos 还款计划
     */
    private void calculateOverdueDays(List<CollectionOrderVo> collectionOrderVos) {
        for (CollectionOrderVo collectionOrderVo : collectionOrderVos) {
            collectionOrderVo.setOverdueDays(DateUtil.daysBetween(collectionOrderVo.getRepaymentDate(), new Date()));
        }
    }

    private Map<String, String> getParamList(ClReceiverInfoEntity clReceiverInfoEntity, Integer overDueDay, String overdueDaysStr) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("name", clReceiverInfoEntity.getName());
        paramMap.put("amount", clReceiverInfoEntity.getBorrowCapital().toString());
//        if (collectionOrderVo.getTotalPeriod() > 1) {
//            paramMap.put("no", collectionOrderVo.getPeriod().toString());
//        }
        String repaymentDate = new SimpleDateFormat("MMM dd", Locale.ENGLISH).format(clReceiverInfoEntity.getRepaymentDate());
        paramMap.put("overdueTime", repaymentDate);
        paramMap.put("overdueDay", overDueDay.toString());
        paramMap.put("overdueDays", overdueDaysStr);
        return paramMap;
    }


}
